import './index.less'
import RoleList from './components/roleList'
import { useEffect, useState } from 'react';
import { handleTreeList } from '@/utils'
import { request } from 'umi';
import { Button, message, Tree } from 'antd'
export default () => {
    const [selectKey, setselectKey] = useState('');
    const [treeData, setTreeData] = useState(null);
    const [checkedKeys, setcheckedKeys] = useState([]);
    const getTreeData = async () => {
        const response: any = await request('/sys/menu/?sourceType=', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            data: {

            },
        });
        let data = handleTreeList(response?.data)
        console.log(data);

        setTreeData(data)
    }
    const getRoleMenus = async () => {
        if (!selectKey) {
            return;
        }
        const response: any = await request(`/sys/role/${selectKey}/permission`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            data: {

            },
        });
        let menudata = response?.data || [];
        let ncheckedKeys = [];
        //遍历menudata 取menuCode
        menudata.forEach((item) => {
            ncheckedKeys.push(item.menuCode)
        })
        setcheckedKeys(ncheckedKeys)
    }
    const sure = () => {
        request(`/sys/role/${selectKey}/permission`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            data: checkedKeys,
        }).then((res) => {
            message.success('保存成功');
        });
    }
    useEffect(() => {
        getTreeData()
    }, [])
    useEffect(() => {
        getRoleMenus();
    }, [selectKey])
    return <div className='rolePage'>
        <div className='role'>
            <RoleList selectKey={selectKey} setselectKey={setselectKey} />
        </div>
        {
            selectKey && treeData && <div className='content'>
                <div className='treeContent'>
                    <Tree
                        checkable
                        // onCheck={onCheck}
                        treeData={treeData}
                        fieldNames={{
                            title: 'menuName',
                            key: 'menuId',
                            children: 'children'
                        }}
                        checkStrictly={false}
                        checkedKeys={checkedKeys}
                        onCheck={(checkedKeysn) => setcheckedKeys(checkedKeysn)}
                    />
                </div>
                <div className='scanContent'>
                    <Button type="primary" onClick={() => sure()}>保存</Button>
                </div>

            </div>


        }


    </div>
}